package com.fei.stormtest;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;

import java.util.*;

/**
 * Created by wangfei23 on 2016/12/30.
 */
public class ReportBolt extends BaseRichBolt {

    private HashMap<String , Long> counts = null;

    @Override
    public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
        this.counts = new HashMap<String , Long>();
    }

    @Override
    public void execute(Tuple tuple) {
        String word = tuple.getStringByField("word");
        Long count = tuple.getLongByField("count");
        this.counts.put(word,count);

    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        // 不在继续发射数据
    }

    public void cleanup(){
        System.out.print("---FINAL COUNTS---");
        List<String> keys = new ArrayList<String>();
        keys.addAll(this.counts.keySet());
        Collections.sort(keys);
        for(String key : keys){
            System.out.println(key + ":" + this.counts.get(key));
        }

        System.out.println("-----------------");
    }
}
